<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="船舶名称">
              <a-input v-model="queryParam.shipName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="mmsi序号">
              <a-input v-model="queryParam.mmsiNumber" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="船舶国籍">
              <a-select @change="val => { queryParam.countryId = val}" v-model="queryParam.countryId">
                <a-select-option v-for="item in shipCountrys" :key="item.countryId" :value="item.countryId">{{ item.shipCountry }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="船舶类型">
              <a-select @change="val => { queryParam.typeId = val}" v-model="queryParam.typeId">
                <a-select-option v-for="item in shipTypes" :key="item.typeId" :value="item.typeId">{{ item.shipType }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="涉疫等级">
              <a-select @change="val => { queryParam.gradeId = val}" v-model="queryParam.gradeId">
                <a-select-option v-for="item in shipEpidemicGrades" :key="item.gradeId" :value="item.gradeId">{{ item.epidemicGrade }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="出发港口">
                <!--                <a-input v-model="queryParam.beginPort" placeholder=""/>-->
                <a-select @change="val => { queryParam.beginPortId = val}" v-model="queryParam.beginPortId">
                  <a-select-option v-for="item in ports" :key="item.portId" :value="item.portId">{{ item.portName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="到达港口">
                <a-select @change="val => { queryParam.targetPortId = val}" v-model="queryParam.targetPortId">
                  <a-select-option v-for="item in ports" :key="item.portId" :value="item.portId">{{ item.portName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="是否在港">
                <a-select @change="val => { queryParam.portStatusId = val}" v-model="queryParam.portStatusId">
                  <a-select-option v-for="item in portStatus" :key="item.portStatusId" :value="item.portStatusId">{{ item.portStatus }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="涉疫类型">
                <a-select @change="val => { queryParam.epidemicTypeId = val}" v-model="queryParam.epidemicTypeId">
                  <a-select-option v-for="item in shipEpidemicTypes" :key="item.epidemicTypeId" :value="item.epidemicTypeId">{{ item.epidemicType }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAddNew">新增船舶到港记录</a-button>
<!--      <a-button type="dashed" icon="search" @click="tableOption">查询指定船舶轨迹</a-button>-->
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="remove">
            <remove-ship ref="removeShip" :shipIds="selectedRowKeys.join(',')" @ok="handleOk"/>
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >

      <a-tag :color="text | stateColorFilter" slot="status" slot-scope="text">{{ text | portStatusTextFilter }}</a-tag>
      <a-tag slot="typeId" :color="text | shipTypeColorFilter " slot-scope="text">{{ text | typeTextFilter }} </a-tag>
      <div slot="countryId" slot-scope="text">{{ text | countryTextFilter }} </div>
      <div slot="epidemicTypeId" slot-scope="text">{{ text | epidemicTypeTextFilter }}</div>
      <a-tag slot="gradeId" :color="text | gradeColorFilter " slot-scope="text">{{ text | epidemicGradeTextFilter }}</a-tag>
      <div slot="beginPortId" slot-scope="text">{{ text | beginPortTextFilter }}</div>
      <div slot="targetPortId" slot-scope="text">{{ text | targetPortTextFilter }}</div>
      <div slot="categoryId" slot-scope="text"> {{ text | categoryTextFilter }}</div>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑 |</a>
          <a @click="handleLeave(record)"> 离港</a>
          <a-divider type="vertical" />
          <remove-ship ref="removeShip" :shipIds="String(record.shipId)" @ok="handleOk"/>
        </template>
      </span>
    </s-table>

    <add-ship ref="addShip" :roles="roles" @ok="handleOk" />
    <edit-ship ref="editShip" :roles="roles" @ok="handleOk"/>
    <leave-port-ship ref="leavePortShip" :roles="roles" @ok="handleOk"/>

  </a-card>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { queryShip } from '@/api/ship/ship'
import AddShip from './modules/ship/AddShip'
import EditShip from './modules/ship/EditShip'
import RemoveShip from './modules/ship/RemoveShip'
import LeavePortShip from './modules/ship/LeavePortShip'
import { queryShipCategory, queryShipCountry, queryShipEpidemicGrade, queryShipEpidemicType, queryShipPort, queryShipPortStatus,  queryShipType } from '@/api/ship/shipDetail'

// 用于处理过滤器动态获取数据
let that

export default {
  name: 'ShipInPort',
  components: {
    STable,
    AddShip,
    EditShip,
    RemoveShip,
    LeavePortShip
  },
  data: function () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 数据数组
      roles: [],
      shipTypes: [],
      shipCountrys: [],
      shipCategorys: [],
      shipEpidemicTypes: [],
      shipEpidemicGrades: [],
      ports: [],
      portStatus: [],
      // 表头
      columns: [
        {
          title: '船舶名称',
          dataIndex: 'shipName',
          align: 'center'
        },
        {
          title: '船舶mmsi序号',
          dataIndex: 'mmsiNumber',
          align: 'center'
        },
        {
          title: '船舶国籍',
          dataIndex: 'countryId',
          align: 'center',
          scopedSlots: { customRender: 'countryId' }
        },
        {
          title: '船舶类型',
          dataIndex: 'typeId',
          align: 'center',
          scopedSlots: { customRender: 'typeId' },
          sorter: false
        },
        {
          title: '涉疫等级',
          dataIndex: 'gradeId',
          align: 'center',
          scopedSlots: { customRender: 'gradeId' },
          sorter: true
        },
        {
          title: '涉疫类型',
          dataIndex: 'epidemicTypeId',
          align: 'center',
          scopedSlots: { customRender: 'epidemicTypeId' },
          sorter: false
        },
        {
          title: '出发港口',
          dataIndex: 'beginPortId',
          scopedSlots: { customRender: 'beginPortId' },
          align: 'center',
          sorter: false
        },
        {
          title: '到达港口',
          dataIndex: 'targetPortId',
          scopedSlots: { customRender: 'targetPortId' },
          align: 'center',
          sorter: false
        },
        {
          title: '出入类别',
          dataIndex: 'categoryId',
          scopedSlots: { customRender: 'categoryId' },
          align: 'center',
          sorter: false
        },
        {
          title: '停泊时间',
          dataIndex: 'berthingTime',
          align: 'center',
          sorter: true,
          scopedSlots: { customRender: 'date' },
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: '离泊时间',
          dataIndex: 'departureTime',
          align: 'center',
          sorter: true,
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          },
        },
        {
          title: '是否在港',
          dataIndex: 'portStatusId',
          align: 'center',
          sorter: true,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
        return queryShip(Object.assign(parameter, queryJson))
          .then(res => {
            // console.log(res)
            return res.result
          })
      },

      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: {
          show: true,
            clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
    roleTextFilter (roleId) {
      let roleName = ''
      for (const role of that.roles) {
        if (parseInt(role.id) === parseInt(roleId)) {
          roleName = role.name
          break
        }
      }
      return roleName
    },
   typeTextFilter (id) {
      let name = ''
      for (const type of that.shipTypes) {
        if (parseInt(type.typeId) === parseInt(id)) {
          name = type.shipType
          break
        }
      }
      return name
    },
    countryTextFilter (id) {
      let name = ''
      for (const country of that.shipCountrys) {
        if (parseInt(country.countryId) === parseInt(id)) {
          name = country.shipCountry
          break
        }
      }
      return name
    },
    portStatusTextFilter (id) {
      let name = ''
      for (const portStatus of that.portStatus) {
        if (parseInt(portStatus.portStatusId) === parseInt(id)) {
          name = portStatus.portStatus
          break
        }
      }
      return name
    },
    epidemicGradeTextFilter (id) {
      let name = ''
      for (const epidemicGrade of that.shipEpidemicGrades) {
        if (parseInt(epidemicGrade.gradeId) === parseInt(id)) {
          name = epidemicGrade.epidemicGrade
          break
        }
      }
      return name
    },
    epidemicTypeTextFilter (id) {
      let name = ''
      for (const epidemicType of that.shipEpidemicTypes) {
        if (parseInt(epidemicType.epidemicTypeId) === parseInt(id)) {
          name = epidemicType.epidemicType
          break
        }
      }
      return name
    },
    beginPortTextFilter (id) {
      let name = ''
      for (const port of that.ports) {
        if (parseInt(port.portId) === parseInt(id)) {
          name = port.portName
          break
        }
      }
      return name
    },
    targetPortTextFilter (id) {
      let name = ''
      for (const port of that.ports) {
        if (parseInt(port.portId) === parseInt(id)) {
          name = port.portName
          break
        }
      }
      return name
    },
    categoryTextFilter (id) {
      let name = ''
      for (const category of that.shipCategorys) {
        if (parseInt(category.categoryId) === parseInt(id)) {
          name = category.shipCategory
          break
        }
      }
      return name
    },
    dateTextFilter (departureTime) {
      if (departureTime === null) {
        return '-'
      }
      return departureTime
    },
    date1TextFilter (berthingTime) {
      console.log(berthingTime)
      if (berthingTime === null) {
        return '-'
      }
      return berthingTime
    },
    statusFilter (key) {
      return key
    },
    stateColorFilter (value) {
      if (value === 1) {
        return 'blue'
      } else {
        return 'green'
      }
    },
    shipTypeColorFilter (value) {
      if (value === 1) {
        return 'skyblue'
      } else {
        return 'peru'
      }
    },
    gradeColorFilter (value) {
      if (value === 1) {
        return 'red'
      } else if (value === 2) {
        return 'yellow'
      } else {
        return 'green'
      }
    }
  },
  beforeCreate() {
    that = this
  },
  created() {
    this.tableOption()
    queryShipType()
      .then(res => {
        // console.log(res)
        this.shipTypes = res.result
      }).catch(() => {
        this.$message.error('获取船舶类型失败')
    })
    queryShipCountry()
      .then(res => {
        // console.log(res)
        this.shipCountrys = res.result
      }).catch(() => {
        this.$message.error('获取船舶国籍信息失败')
    })
    queryShipPort()
      .then(res => {
        // console.log(res)
        this.ports = res.result
      }).catch(() => {
        this.$message.error('获取港口信息失败')
    })
    queryShipPortStatus()
      .then(res => {
        console.log(res)
        this.portStatus = res.result
      }).catch(() => {
        this.$message.error('获取船舶在港信息失败')
    })
    queryShipEpidemicType()
      .then(res => {
        // console.log(res)
        this.shipEpidemicTypes = res.result
      }).catch(() => {
        this.$message.error('获取船舶涉疫类型失败')
    })
    queryShipEpidemicGrade()
      .then(res => {
        // console.log(res)
        this.shipEpidemicGrades = res.result
      }).catch(() => {
        this.$message.error('获取船舶涉疫等级失败')
    })
    queryShipCategory()
      .then(res => {
        // console.log(res)
        this.shipCategorys = res.result
      }).catch(() => {
        this.$message.error('获取船舶出入类型失败')
    })
  },
  methods: {
    tableOption () {
      if (this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleEdit (record) {
      this.$refs.editShip.shipTypes = this.shipTypes
      this.$refs.editShip.shipCountrys = this.shipCountrys
      this.$refs.editShip.shipCategorys = this.shipCategorys
      this.$refs.editShip.shipEpidemicTypes = this.shipEpidemicTypes
      this.$refs.editShip.shipEpidemicGrades = this.shipEpidemicGrades
      this.$refs.editShip.ports = this.ports
      this.$refs.editShip.edit(record)
    },
    handleLeave (record) {
      this.$refs.leavePortShip.leave(record)
    },
    handleOk () {
      this.$refs.table.clearSelected()
      this.$refs.table.refresh(false)
    },
    // shipTypes: [],
    // shipCountrys: [],
    // shipCategorys: [],
    // shipEpidemicTypes: [],
    // shipEpidemicGrades: [],
    handleAddNew () {
      this.$refs.addShip.add()
      this.$refs.addShip.shipTypes = this.shipTypes
      this.$refs.addShip.shipCountrys = this.shipCountrys
      this.$refs.addShip.shipCategorys = this.shipCategorys
      this.$refs.addShip.shipEpidemicTypes = this.shipEpidemicTypes
      this.$refs.addShip.shipEpidemicGrades = this.shipEpidemicGrades
      this.$refs.addShip.ports = this.ports
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
